package com.example.ucenter.controller;

import com.example.common.exception.GuliException;
import com.example.ucenter.service.MemberService;
import com.example.ucenter.utils.HttpClientUtils;
import com.example.ucenter.utils.WxConstUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author:tjf
 * @Description:
 */
@Controller
@Tag(name = "微信接口控制器")
@RequestMapping("/api/ucenter/wx")
public class WxApiController {
    @Resource
    private MemberService memberService;
    @Operation(description = "微信用户扫码成功后调用的方法")
    @GetMapping("/callback")
    public String callback(String code){
        String token = memberService.loginByWxCode(code);
        if (StringUtils.isBlank(token)){
            throw new GuliException(20001, "登录失败！");
        }
        // 重定向应用主页面
        return "redirect:http://localhost:3000?token=" + token;
    }

    @Operation(description = "通过重定向执行网址获取微信登录二维码")
    @GetMapping("/login")
    public String getWxCode(){
        String url = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=%s&scope=%s&state=%s#wechat_redirect";
        String redirectUrl = URLEncoder.encode(WxConstUtils.WX_OPEN_REDIRECT_URL);

        // 格式化url
        url = String.format(url, WxConstUtils.WX_OPEN_APP_ID, redirectUrl, "code", "snsapi_login", "atguigu");

        return "redirect:" + url;
    }
}
